package net.ankao.job.common;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;
import java.text.DecimalFormat;

/**
 * @author LILU
 * @date 2025-01-06 16:24
 */
public class CustomDoubleSerializer extends StdSerializer<Double> {

    private static final long serialVersionUID = 1L;

    public CustomDoubleSerializer() {
        this(null);
    }

    public CustomDoubleSerializer(Class<Double> t) {
        super(t);
    }

    @Override
    public void serialize(Double value, JsonGenerator gen, SerializerProvider provider)
            throws IOException {
        if (value != null) {
            // Only show decimal places if they are not zero
            DecimalFormat df = new DecimalFormat("#.##");
            df.setGroupingUsed(false); // Optional: removes grouping separators

            // Format the double and remove trailing zeros after decimal point
            String formattedValue = df.format(value);

            gen.writeString(formattedValue);
        } else {
            gen.writeNull();
        }
    }

}